<?php
/**
 * Created by PhpStorm.
 * User: wuchao
 * Date: 2020/5/19
 * Time: 15:36
 */

namespace app\api\controller\v1\home;

use app\middleware\ApiAuth;
use think\Request;
use think\facade\Validate;
use think\response\Json;
use think\validate\ValidateRule;
use app\api\model\OrderModel;
use think\facade\Db;
use \Exception as E;

class Order
{
//    protected $middleware = [ApiAuth::class];

    /**
     * @desc 生成订单
     * @return Json
     */
    public function NewOrder(Request $request)
    {
        $input['goodsData'] = $request->post('goodsData');//商品数据
        $input['role_type'] = $request->post('role_type');//用户ID
        $input['uid'] = $request->post('uid');//用户ID
        $input['addressID'] = $request->post('addressID');//用户地址ID
        $input['total'] = $request->post('total');//商品总价
        $input['admin_id'] = $request->post('admin_id');//运营商ID
        $input['remark'] = $request->post('remark');//备注
        $input['group_id'] = $request->post('group_id');//公司id
        $input['is_believe'] = $request->post('is_believe');//1:授信 0：非授信'
        $input['cart_id'] = $request->post('cart_id');//购物车ID
        $input['pay_type'] = $request->post('pay_type', 0);//
        // 参数校验
        $validate = Validate::rule([
            'goodsData' => ValidateRule::isRequire(),
            'uid' => ValidateRule::isRequire(),
            'addressID' => ValidateRule::isRequire(),
            'total' => ValidateRule::isRequire(),
            'admin_id' => ValidateRule::isRequire(),
            'role_type' => ValidateRule::isRequire(),
            'group_id' => ValidateRule::isRequire(),
            'is_believe' => ValidateRule::isRequire(),
            'cart_id' => ValidateRule::isRequire(),
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        //逻辑处理
        return OrderModel::NewOrder($input);
    }

    /**订单列表
     * @param Request $request
     */
    public function OrderList(Request $request)
    {
        $input['group_id'] = $request->param('group_id');//用户ID
        $input['page'] = $request->param('page', 1);//页数
        $input['limit'] = $request->param('limit', 20);//条数
        $input['status'] = $request->param('status');//根据状态获取订单,特殊 A：全部订单 //待支付
        // 参数校验
        $validate = Validate::rule([
            'group_id' => ValidateRule::isRequire(),
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        //逻辑处理
        return OrderModel::OrderList($input);
    }

    /**订单列表
     * @param Request $request
     */
    public function OrderNum(Request $request)
    {
        $input['group_id'] = $request->param('group_id');//用户ID
        $validate = Validate::rule([
            'group_id' => ValidateRule::isRequire(),
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        //逻辑处理
        //待支付
        $data['wait_pay'] = Db::table('order')->where('group_id', $input['group_id'])->where('is_pay', 0)->where('status', 0)->group('mastr_order_no')->count();
        //待发货
        $data['wait_send'] = Db::table('order')->where('group_id', $input['group_id'])->where('is_pay', 0)->where('status', 1)->group('mastr_order_no')->count();
        //待收货
        $data['wait_receipt'] = Db::table('order')->where('group_id', $input['group_id'])->where('is_pay', 0)->where('status', 3)->group('mastr_order_no')->count();
        //待评价
        $data['wait_reply'] = Db::table('order')->where('group_id', $input['group_id'])->where('is_pay', 0)->where('status', 5)->group('mastr_order_no')->count();
//        $data['is_pay'] = Db::table('order')->where('group_id',$input['group_id'])->where('is_pay',0)->count();
        return jsonSuccess('获取成功', $data);
    }

    /**用户申请退款
     * @param Request $request
     */
    public function ApplyRefund(Request $request)
    {
        $input['back_reason'] = $request->param('back_reason');//退款理由
        $input['image'] = $request->file('image');
        $input['order_no'] = $request->param('order_no');//订单编号
        // 参数校验
        $validate = Validate::rule([
            'back_reason' => ValidateRule::isRequire(),
            'order_no' => ValidateRule::isRequire(),
            'image' => ValidateRule::isRequire(null, '缺少参数')
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        //逻辑处理
        return OrderModel::ApplyRefund($input, $request->scheme() . '://' . $request->host());
    }

    /**用户订单评论
     * @param Request $request
     */
    public function GoodsReply(Request $request)
    {
        $input['goods_id'] = $request->param('goods_id');//退款理由
        $input['comment'] = $request->param('comment', '');//评论内容
        $input['image'] = $request->file('image');//图片
        $input['uid'] = $request->param('uid');//用户ID
        $input['oid'] = $request->param('oid');//订单ID
        $input['goods_score'] = $request->param('goods_score', 5);//商品分数
        $input['service_score'] = $request->param('service_score', 5);//服务分数
        $input['admin_id'] = $request->param('admin_id');//运营商ID
        // 参数校验
        $validate = Validate::rule([
            'goods_id' => ValidateRule::isRequire(),
            'uid' => ValidateRule::isRequire(),
            'oid' => ValidateRule::isRequire(),
            'admin_id' => ValidateRule::isRequire(),
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        //逻辑处理
        return OrderModel::GoodsReply($input, $request->scheme() . '://' . $request->host());
    }

    /**用户收货
     * @param Request $request
     */
    public function GoodsReceipt(Request $request)
    {
        $input['oid'] = $request->param('oid');//订单ID
        $input['uid'] = $request->param('uid');//订单ID
        // 参数校验
        $validate = Validate::rule([
            'oid' => ValidateRule::isRequire(),
            'uid' => ValidateRule::isRequire(),
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        try {
            Db::startTrans();
            $user = Db::table('user')->where('id', $input['uid'])->field('name,phone,role_type')->find();
            $res = Db::table('order')->where('id', $input['oid'])->update(['status' => 4]);
            $red = Db::table('order_status')->insertGetId([
                'oid' => $input['oid'],
                'change_message' => '订单已收货，收货人ID：' . $input['uid'] . '， 收货人姓名：' . $user['name'] . '，收货人电话：' . $user['phone'],
                'name' => $user['name'],
                'phone' => $user['phone'],
                'role_type' => $user['role_type'] == 1 ? '老板' : '员工',
                'create_time' => time(),
            ]);
            if ($res != 0 && $red != 0) {
                Db::commit();
                return jsonSuccess('收货成功');
            } else {
                Db::rollback();
                return jsonFail('收货失败', $res);
            }
        } catch (E $e) {
            Db::rollback();
            return jsonFail('系统错误~', $e->getMessage());
        }
    }

}